<?php


namespace app\common\service;


use think\exception\HttpResponseException;
use think\facade\Request;
use think\Response;
use ipip\db\District;

/**
 * 工具类
 * @author 贾二小
 * @since 2021/3/28
 */
class ToolsService
{

    /**
     * 返回成功的操作
     * @param mixed $data
     * @param int $code 0返回表格｜200返回数据
     * @param string $msg
     * @param string $logName
     * @param string $logMsg
     * @param string $account
     * @author 贾二小
     * @since 2021/3/28
     */
    public static function success($data, int $code, string $msg, string $logName, string $logMsg, string $account)
    {
        if($code === 0){
            $result = ['success'=>true, 'code' => 0, 'message'=>$msg, 'data' => $data['data'], 'count'=>$data['count'], 'page'=>intval(input('page',1)), 'limit'=>intval(input('limit',10))];
        }elseif ($code === 200){
            $result = ['success'=>true, 'code' => $code, 'message' => $msg, 'data' => $data];
        }else{
            $result = ['success'=>false, 'code' => $code, 'message' => $msg, 'data' => $data];
        }
        //返回页面数据
        $response = Response::create($result, 'json', 200);
        //记录日志
        if($result['success']){
            self::visLog($logName,$logMsg,$account,$response->getContent());
        }else{
            self::visLog($logName,$logMsg,$account,$response->getContent(), 'N');
        }
        throw new HttpResponseException($response);
    }

    /**
     * 重定向
     * @author 贾二小
     * @since 2021/8/2
     */
    public static function redirect($url, $logName,$logMsg,$account){
        self::visLog($logName,$logMsg,$account);
        throw new HttpResponseException(Response::create($url, 'redirect', 302));
    }

    /**
     * 记录日志
     * @author 贾二小
     * @since 2021/8/2
     */
    public static function visLog($name, $message, $account, $result='', $success='Y'){
        //日志类型为空不记录日志
        if(empty($name)){
            return false;
        }
        $data = [];
        $data['name'] = $name;
        $data['success'] = $success;
        $data['message'] = $message;
        $data['ip'] = get_client_ip(0,true);
        $data['location'] = self::getIPAddress($data['ip']);
        $data['browser'] = self::getClientBrowser();
        $data['os'] = self::getClientOS();
        $data['account'] = $account;
        if($name == '用户登录' || $name == '用户登出'){
            $data['vis_type'] = $name == '用户登录' ? 1:2;
            $data['vis_time'] = datetime(Request::time());
            \think\facade\Db::name('vis_log')->insert($data);
            return true;
        }
        $data['url'] = Request::url();
        $data['class_name'] = Request::controller();
        $data['method_name'] = Request::action();
        $data['req_method'] = Request::method(true);
        $data['param'] = json_encode(Request::param(),JSON_UNESCAPED_UNICODE);
        $data['result'] = $result;
        $data['op_time'] = datetime(Request::time());
        \think\facade\Db::name('op_log')->insert($data);
        return true;
    }

    /**
     * 根据IP获取省市
     * https://www.ipip.net/product/ip.html
     * @author 贾二小
     * @since 2021/8/1
     */
    private static function getIPAddress($ip): string
    {
        if(!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)){
            return '';
        }
        $district = new District(app()->getRootPath().'ipdb/free.ipdb');
        return implode(' ',array_unique($district->find($ip, 'CN')));
    }

    /**
     * 阿里云根据IP获取省市
     * @author 贾二小
     * @since 2021/9/2
     */
    private static function getAliyunIPAddress($ip): string
    {
        if(!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)){
            return '';
        }
        $headers = [];
        array_push($headers, "Authorization:APPCODE " . get_config('aliyunAppCode'));
        $url = "http://iploc.market.alicloudapi.com/v3/ip?ip=" . $ip;
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "GET");
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_TIMEOUT, 300);
        // 执行命令
        $result = curl_exec($curl);
        // 关闭URL请求(释放句柄)
        curl_close($curl);
        if ($result === false) {
            return '';
        }
        $result = json_decode($result,true);
        $result['ip'] = $ip;
        return $result['province'].' '.$result['city'];
    }

    /**
     * 获取客户端操作系统
     * @author 贾二小
     * @since 2021/8/2
     */
    private static function getClientOS(): string
    {
        $agent = $_SERVER['HTTP_USER_AGENT'];
        $os_ver = '';
        //window系统
        if (stripos($agent, 'window')) {
            $os = 'Windows';
            if (preg_match('/nt 6.0/i', $agent)) {
                $os_ver = 'Vista';
            }elseif(preg_match('/nt 10.0/i', $agent)) {
                $os_ver = '10';
            }elseif(preg_match('/nt 6.3/i', $agent)) {
                $os_ver = '8.1';
            }elseif(preg_match('/nt 6.2/i', $agent)) {
                $os_ver = '8.0';
            }elseif(preg_match('/nt 6.1/i', $agent)) {
                $os_ver = '7';
            }elseif(preg_match('/nt 5.1/i', $agent)) {
                $os_ver = 'XP';
            }elseif(preg_match('/nt 5/i', $agent)) {
                $os_ver = '2000';
            }elseif(preg_match('/nt 98/i', $agent)) {
                $os_ver = '98';
            }elseif(preg_match('/nt/i', $agent)) {
                $os_ver = 'nt';
            }else{
                $os_ver = '';
            }
            if (preg_match('/x64/i', $agent)) {
                $os .= '(x64)';
            }elseif(preg_match('/x32/i', $agent)){
                $os .= '(x32)';
            }
        }
        elseif(stripos($agent, 'linux')) {
            if (stripos($agent, 'android')) {
                preg_match('/android\s([\d\.]+)/i', $agent, $match);
                $os = 'Android';
                $os_ver = $match[1];
            }else{
                $os = 'Linux';
            }
        }
        elseif(stripos($agent, 'unix')) {
            $os = 'Unix';
        }
        elseif(preg_match('/iPhone|iPad|iPod/i',$agent)) {
            preg_match('/OS\s([0-9_\.]+)/i', $agent, $match);
            $os = 'IOS';
            $os_ver = str_replace('_','.',$match[1]);
        }
        elseif(stripos($agent, 'mac os')) {
            preg_match('/Mac OS X\s([0-9_\.]+)/i', $agent, $match);
            $os = 'Mac OS X';
            $os_ver = str_replace('_','.',$match[1]);
        }
        else {
            $os = 'Other';
        }
        return $os.'_'.$os_ver;
    }

    /**
     * 获取客户端浏览器以及版本号
     * @author 贾二小
     * @since 2021/8/2
     */
    private static function getClientBrowser(): string
    {
        $agent = $_SERVER['HTTP_USER_AGENT'];
        $browser = '';
        $browser_ver = '';
        if (preg_match('/OmniWeb\/(v*)([^\s|;]+)/i', $agent, $regs)) {
            $browser = 'OmniWeb';
            $browser_ver = $regs[2];
        }
        if (preg_match('/Netscape([\d]*)\/([^\s]+)/i', $agent, $regs)) {
            $browser = 'Netscape';
            $browser_ver = $regs[2];
        }
        if (preg_match('/safari\/([^\s]+)/i', $agent, $regs)) {
            $browser = 'Safari';
            $browser_ver = $regs[1];
        }
        if (preg_match('/MSIE\s([^\s|;]+)/i', $agent, $regs)) {
            $browser = 'Internet Explorer';
            $browser_ver = $regs[1];
        }
        if (preg_match('/Opera[\s|\/]([^\s]+)/i', $agent, $regs)) {
            $browser = 'Opera';
            $browser_ver = $regs[1];
        }
        if (preg_match('/NetCaptor\s([^\s|;]+)/i', $agent, $regs)) {
            $browser = '(Internet Explorer '.$browser_ver.') NetCaptor';
            $browser_ver = $regs[1];
        }
        if (preg_match('/Maxthon/i', $agent, $regs)) {
            $browser = '(Internet Explorer '.$browser_ver.') Maxthon';
            $browser_ver = '';
        }
        if (preg_match('/360SE/i', $agent, $regs)) {
            $browser = '(Internet Explorer '.$browser_ver.') 360SE';
            $browser_ver = '';
        }
        if (preg_match('/SE 2.x/i', $agent, $regs)) {
            $browser = '(Internet Explorer '.$browser_ver.') 搜狗';
            $browser_ver = '';
        }
        if (preg_match('/FireFox\/([^\s]+)/i', $agent, $regs)) {
            $browser = 'FireFox';
            $browser_ver = $regs[1];
        }
        if (preg_match('/Lynx\/([^\s]+)/i', $agent, $regs)) {
            $browser = 'Lynx';
            $browser_ver = $regs[1];
        }
        if (preg_match('/Chrome\/([^\s]+)/i', $agent, $regs)) {
            $browser = 'Chrome';
            $browser_ver = $regs[1];
        }
        if (preg_match('/MicroMessenger\/([^\s]+)/i', $agent, $regs)) {
            $browser = '微信浏览器';
            $browser_ver = $regs[1];
        }
        return $browser.'_'.$browser_ver;
    }


}